package com.sptpc.qimoxiangmu.util;

import cn.hutool.core.util.NumberUtil;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.springframework.format.Formatter;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.util.Locale;

//@Component
//public class MoneyFormatter implements Formatter<Money> {
//    @Override
//    public Money parse(String s, Locale locale) throws ParseException {
//        if(NumberUtil.isNumber(s)){//判断字符是否为s,是数字字符串
//            return Money.of(CurrencyUnit.of("CNY"),NumberUtil.toBigDecimal(s));
//             }
//        throw  new ParseException(s,0);//不是字符串抛出异常
//}
//
//    @Override
//    public String print(Money money, Locale locale) {
//        if(money==null){
//            return  null;
//        }
//        return money.getCurrencyUnit().getCode()+" "+money.getAmount();
//    }
//}
@Component
public class MoneyFormatter implements Formatter<Money> {
    @Override
    public Money parse(String s, Locale locale) throws ParseException {
        if (NumberUtil.isNumber(s)) {
            return Money.of(CurrencyUnit.of("CNY"), NumberUtil.toBigDecimal(s));
        }
        throw new ParseException(s, 0);
    }

    @Override
    public String print(Money money, Locale locale) {
        if (money == null) {
            return null;
        }
        return money.getCurrencyUnit().getCode() + " " + money.getAmount();
    }
}